<?php

namespace App\Http\Controllers\Backend;

use App\Http\Requests\Backend\EditUser;
use App\Http\Requests\Backend\StoreUser;
use App\Http\Resources\Backend\UserResource;
use App\Models\AdminLog;
use App\Models\SchoolRule;
use App\Models\User;
use Illuminate\Http\Request;

/**
 * Class UserController
 * @package App\Http\Controllers\Backend
 * 用户管理控制器
 */
class UserController extends BackendController
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     * 用户管理列表
     */
    public function index(Request $request)
    {
        $users = User::orderBy('created_at', 'desc')
            ->with(['school', 'role'])
            ->phoneLike($request->phone)
            ->nameLike($request->name)
            ->from($request->source_from)
            ->schoolIs($request->school_id)
            ->roleIs($request->role_id)
            ->paginate($request->size);
        return UserResource::collection($users);
    }

    /**
     * @param StoreUser $request
     * @return UserResource|array
     * 新增用户信息
     */
    public function store(StoreUser $request)
    {
        $schoolRule = SchoolRule::query()->where('school_id', $request->school_id)->first();
        $user = User::create(array_merge($request->all(), [
            'source_from' => 'backend',
            'morning_rule' => $schoolRule->morning_rule,
            'lunch_rule' => $schoolRule->lunch_rule,
            'dinner_rule' => $schoolRule->dinner_rule
        ]));
        AdminLog::log('新增用户' . $user->name);
        return new UserResource($user);
    }

    /**
     * @param EditUser $request
     * @param User $user
     * @return UserResource|array
     * 编辑用户
     */
    public function update(EditUser $request, User $user)
    {
        $user->fill($request->all());
        $user->save();
        AdminLog::log('编辑用户' . $user->name);
        return new UserResource($user);
    }

    /**
     * @param User $user
     * @return UserResource
     * 启用/禁用用户
     */
    public function destroy(User $user)
    {
        if ($user->status === User::ACTIVE) {
            $user->status = User::DISABLED;
            $user->save();
            AdminLog::log('禁用用户' . $user->name);
        } else {
            $user->status = User::ACTIVE;
            $user->save();
            AdminLog::log('启用用户' . $user->name);
        }
        return new UserResource($user);
    }
}
